package cn.liangjintang.webserver;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.ActivityCompat;
import android.util.Log;
import android.widget.Toast;

import java.io.File;

public class MainActivity extends Activity implements ActivityCompat.OnRequestPermissionsResultCallback {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        int flag = PermissionUtils.verifyStoragePermissions(this);
        if (flag == 0) {
            toGotoWebServerActivity();
        }
    }

    private void toGotoWebServerActivity() {
        Log.d(getClass().getSimpleName(), "toGotoWebServerActivity...");
        Intent intent = new Intent(this, WebServerActivity.class);
        this.startActivity(intent);
        finish();
    }

    private void toGotoFinish() {
        Toast.makeText(this, "文件服务器需要申请读写权限", Toast.LENGTH_SHORT).show();
        Log.d(getClass().getSimpleName(), "文件服务器需要申请读写权限,重启后重新设置...");
        finish();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (requestCode == PermissionUtils.REQUEST_EXTERNAL_STORAGE) {
            boolean b = true;
            for (int i = 0; i < permissions.length; i++) {
                Log.d(getClass().getSimpleName(), "申请：" + permissions[i] + " " + (grantResults[i] == PackageManager.PERMISSION_GRANTED ? "成功" : "失败"));
                if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                    b = false;
                    break;
                }
            }
            if (b) {
                toGotoWebServerActivity();
            } else {
                toGotoFinish();
            }
        }
    }
}
